package middleware

import (
	"context"
	"fmt"
	"golang.org/x/time/rate"
	"net/http"
)

func GlobalLimiterMiddleware(limiter *rate.Limiter) func(next http.HandlerFunc) http.HandlerFunc {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			// 从上下文中获取限流器
			ctx := r.Context()
			rl, ok := ctx.Value("GlobalLimiter").(*rate.Limiter)
			if !ok {
				// 如果上下文中没有限流器，则初始化
				rl = limiter
				ctx = context.WithValue(ctx, "GlobalLimiter", rl)
				r = r.WithContext(ctx)
			}

			// 进行限流控制
			if !rl.Allow() {
				// 超过限制，返回错误
				//w.WriteHeader(http.StatusOK)
				// StatusTooManyRequests              = 429 // RFC 6585, 4
				//w.Write([]byte(`{"status": 429, "msg": "too many requests"}`))
				fmt.Println("[Warning] 全局限流.")
				http.Error(w, `{"status": 429, "msg": "too many requests"}`, http.StatusOK)
				return
			}

			// 继续执行下一个中间件或处理函数
			next(w, r)
		}
	}
}
